import backtrader as bt

# 案例一：成交量突破与价格趋势确认
class VolumeBreakoutStrategy(bt.Strategy):
    params = (
        ("volume_multiplier", 2),  # 成交量倍数阈值
        ("price_move_threshold", 0.01),  # 价格变动阈值
    )

    def __init__(self):
        self.volume_breakout = False
        self.price_trend = None
        self.order = None

    def next(self):
        if len(self.data) > 1:
            prev_volume = self.data.volume[-1]
            current_volume = self.data.volume[0]
            if current_volume > prev_volume * self.params.volume_multiplier:
                self.volume_breakout = True

            prev_close = self.data.close[-1]
            current_close = self.data.close[0]
            if current_close > prev_close:
                self.price_trend = "up"
            elif current_close < prev_close:
                self.price_trend = "down"

            if self.volume_breakout and self.price_trend == "up":
                if not self.position:
                    self.order = self.buy()
            elif self.volume_breakout and self.price_trend == "down":
                if self.position:
                    self.order = self.sell()

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            return

        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    f"BUY EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            elif order.issell():
                self.log(
                    f"SELL EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            self.order = None

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log("Order Canceled/Margin/Rejected")

    def log(self, txt):
        dt = self.datas[0].datetime.date(0)
        print(f"{dt}, {txt}")


if __name__ == "__main__":
    cerebro = bt.Cerebro()
    data = bt.feeds.GenericCSVData(
        dataname="your_data.csv",
        dtformat=("%Y-%m-%d"),
        datetime=0,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1,
    )
    cerebro.adddata(data)
    cerebro.addstrategy(VolumeBreakoutStrategy)
    cerebro.broker.setcash(100000.0)
    cerebro.broker.setcommission(commission=0.001)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
